package com.zh.search.service.impl;

import cn.hutool.core.util.StrUtil;
import com.zh.common.exception.BusinessException;
import com.zh.search.dataSource.ArticleEsDataSource;
import com.zh.search.dataSource.EsDataSource;
import com.zh.search.dataSource.DataSourceRegistry;
import com.zh.search.domain.dto.SearchDto;
import com.zh.search.domain.vo.SearchVo;
import com.zh.search.service.ISearchService;
import com.zh.web.base.PageApiResult;
import org.springframework.stereotype.Service;

/**
 * 外观模式
 */
@Service
public class SearchServiceImpl implements ISearchService {

    private final DataSourceRegistry dataSourceRegistry;

    SearchServiceImpl(DataSourceRegistry dataSourceRegistry) {
        this.dataSourceRegistry = dataSourceRegistry;
    }

    @Override
    public SearchVo doSearch(SearchDto searchDto) {
        searchDto.setPageNum(searchDto.getPageNum() <= 0L ? 1L : searchDto.getPageNum());
        searchDto.setPageSize(searchDto.getPageSize() <= 0L ? 10L : searchDto.getPageSize());
//        if (StrUtil.isEmpty(keyword)) {
//            throw new BusinessException("搜索关键字可以为空");
//        }
        if (searchDto.getSearchType() == null) {
            //搜全部
            return null;
        }
        //搜指定类型
        EsDataSource<?> esDataSource = dataSourceRegistry.getDataSourceByType(searchDto.getSearchType());
        PageApiResult<?> pageApiResult = esDataSource.doSearch(searchDto);//构造结果
        SearchVo searchVo = new SearchVo();
        searchVo.setPageNum(pageApiResult.getPageNum());
        searchVo.setPageSize(pageApiResult.getPageSize());
        searchVo.setList(pageApiResult.getList());
        return searchVo;
    }
}
